let articleModel = require('../module/articleModel'),
    moment = require('moment'),
    mditor = require("mditor");

// 将时间设置成中文
moment.locale('zh-cn');

module.exports = {
    //发表文章:
    handlePostArticle: (req, res) => {
        //获取到表单提交的信息:
        let newArticle = req.body;
        //给表单里面添加一个时间参数:
        newArticle.ctime = new Date();

        //调用module模块:
        articleModel.addArticle(newArticle, (err, data) => {
            if (err) return res.json({
                status: 0,
                msg: '查询数据库失败'
            });
            res.json({
                status: 1,
                articleId: data.insertId
            })
        })
    },

    //展示详情页:
    showDetailPage: (req, res) => {
        //获取到url中的参数id:
        let articleId = req.query.id;

        articleModel.getDetail(articleId, (err, data) => {

            // console.log(err);
            // console.log(data);
            if (err) return res.json({
                status: 0,
                msg: '操作是数据库失败'
            });
            //在数据渲染之前处理一下:
            data[0].ctime = moment(data[0].ctime).format('MM-DD-YYYY');
            //将内容从markdown 转换成html字符串,利用mditor.Parser();
            let parser = new mditor.Parser();
            data[0].content = parser.parse(data[0].content);
            //渲染页面:
            res.render('article/detail', {
                article: data[0],
                isLogin: req.session.isLogin,
                user: req.session.user
            })
        })
    },

    // 显示编辑文章页面的controller
    showEditPage: (req, res) => {
        let id = req.query.id
        articleModel.queryArticleById(id, (err, data) => {

            if (err) return res.json({
                status: 0,
                msg: '操作数据库失败'
            })
            if (!req.session.isLogin) return res.redirect('/')
            res.render('article/edit', {
                article: data[0],
                user: req.session.user
            })
        })
    },

    // 7.4 编辑文章的controller
    handleEdit: (req, res) => {
        let article = req.body
        article.ctime = new Date()

        articleModel.updateArticleById(article, (err, data) => {

            if (err) return res.json({
                status: 0,
                msg: '操作数据库失败'
            })
            // 这里articleId必须传递，因为前台渲染跳转到详情页时必须要这个文章id
            res.json({
                status: 1,
                articleId: article.id
            })
        })
    }
}